package com.one.blocks.security.authc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.one.blocks.common.enums.CodeMsgEnum;
import com.one.blocks.common.response.ResponseHelper;
import com.one.blocks.security.enums.SecurityExceptionEnum;
import com.one.blocks.security.exception.AuthcException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-09-24 10:04:51
 */

@Slf4j
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    public RestAuthenticationEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        CodeMsgEnum reason;
        if (authException instanceof AuthcException) {
            reason = ((AuthcException) authException).getCodeMsgEnum();
            log.info("认证异常!msg={}", reason.getMsg());
        } else {
            reason = SecurityExceptionEnum.NO_ACCESS_TOKEN;
            log.info("认证异常!msg={}", authException.getMessage());
        }
        String resBody = objectMapper.writeValueAsString(ResponseHelper.fail(reason));
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.print(resBody);
            printWriter.flush();
        }
    }
}
